package cn.tqfeiyang.smartadmin.system.mapper;

import cn.tqfeiyang.smartadmin.system.entity.PermissionEntity;
import cn.tqfeiyang.smartadmin.system.entity.RoleEntity;
import cn.tqfeiyang.smartadmin.system.entity.RolePermissionEntity;
import cn.tqfeiyang.smartadmin.system.entity.RolePermissionEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

/**
 * 角色-权限映射接口
 *
 * @author tqfeiyang
 * @since 2024/8/20 14:15
 */
@Mapper
public interface RolePermissionMapper extends BaseMapper<RolePermissionEntity> {

    @Select("SELECT p.* FROM sys_role_permission rp JOIN sys_permission p ON p.permission_id = rp.permission_id WHERE rp.role_id = #{roleId}")
    List<PermissionEntity> selectPermissionListByRoleId(Long roleId);

    @Insert("<script>"
            + "INSERT INTO sys_role_permission(role_id, permission_id) "
            + "SELECT #{roleId}, permission_id "
            + "FROM sys_permission "
            + "WHERE permission_id IN "
            + "<foreach item='id' index='index' collection='permissionIds' open='(' separator=',' close=')'>"
            + "#{id}"
            + "</foreach>"
            + "</script>")
    int insertPermissionIdsByRoleId(Long roleId, Set<Long> permissionIds);

    @Delete("DELETE FROM sys_role_permission WHERE role_id = #{roleId}")
    void deletePermissionIdsByRoleId(Long roleId);

    @Select("SELECT r.* FROM sys_role_permission rp JOIN sys_role r ON r.role_id = rp.role_id WHERE rp.permission_id = #{permissionId}")
    List<RoleEntity> selectRoleListByPermissionId(Long permissionId);

    @Insert("<script>"
            + "INSERT INTO sys_role_permission(permission_id, role_id) "
            + "SELECT #{permissionId}, role_id "
            + "FROM sys_role "
            + "WHERE role_id IN "
            + "<foreach item='id' index='index' collection='roleIds' open='(' separator=',' close=')'>"
            + "#{id}"
            + "</foreach>"
            + "</script>")
    int insertRoleIdsByPermissiond(Long permissionId, Set<Long> roleIds);

    @Delete("DELETE FROM sys_role_permission WHERE permission_id = #{permissionId}")
    void deleteRoleIdsByPermissionId(Long permissionId);

}
